<template>
  <div class="design-canvas">
    <!-- 画布工具栏 -->
    <div class="canvas-toolbar">
      <div class="toolbar-left">
        <el-button-group>
          <el-button 
            size="small" 
            :type="zoomMode === 'fit' ? 'primary' : ''"
            @click="setZoomMode('fit')"
          >
            适应画布
          </el-button>
          <el-button 
            size="small" 
            :type="zoomMode === '100' ? 'primary' : ''"
            @click="setZoomMode('100')"
          >
            100%
          </el-button>
        </el-button-group>
        
        <el-button-group>
          <el-button 
            size="small" 
            icon="el-icon-zoom-in"
            @click="zoomIn"
          />
          <el-button 
            size="small" 
            icon="el-icon-zoom-out"
            @click="zoomOut"
          />
        </el-button-group>
        
        <span class="zoom-level">{{ Math.round(zoomLevel * 100) }}%</span>
      </div>
      
      <div class="toolbar-right">
        <el-button 
          size="small" 
          icon="el-icon-refresh-left"
          @click="resetCanvas"
        >
          重置
        </el-button>
        <el-button 
          size="small" 
          icon="el-icon-view"
          @click="toggleGrid"
        >
          {{ showGrid ? '隐藏网格' : '显示网格' }}
        </el-button>
      </div>
    </div>
    
    <!-- 画布容器 -->
    <div 
      ref="canvasContainer"
      class="canvas-container"
      :class="{ 'show-grid': showGrid }"
      @drop="handleDrop"
      @dragover="handleDragOver"
      @dragleave="handleDragLeave"
      @click="handleCanvasClick"
    >
      <!-- 网格背景 -->
      <div v-if="showGrid" class="grid-background"></div>
      
      <!-- 画布内容 -->
      <div 
        class="canvas-content"
        :style="canvasStyle"
      >
                 <!-- 页面组件 -->
         <template v-if="pageConfig && pageConfig.components">
           <ComponentRenderer
             v-for="component in pageConfig.components"
             :key="component.id"
             :component="component"
             :is-selected="isComponentSelected(component)"
             :is-preview="false"
             @click="handleComponentClick"
             @dblclick="handleComponentDoubleClick"
             @drag-start="handleComponentDragStart"
             @update="handleComponentUpdate"
             @delete="handleComponentDelete"
           />
         </template>
        
        <!-- 空画布提示 -->
        <div v-if="!pageConfig?.components?.length" class="empty-canvas">
          <div class="empty-tip">
            <i class="el-icon-plus"></i>
            <h3>开始设计</h3>
            <p>从左侧组件库拖拽组件到画布中</p>
          </div>
        </div>
      </div>
      
      <!-- 拖拽高亮区域 -->
      <div 
        v-if="dragState.isDragging && dragState.dropTarget"
        class="drop-highlight"
        :style="dropHighlightStyle"
      >
        <div class="highlight-border"></div>
      </div>
    </div>
    
    <!-- 画布状态栏 -->
    <div class="canvas-statusbar">
      <div class="status-left">
        <span>页面: {{ pageConfig?.name || '未命名页面' }}</span>
        <span>组件: {{ pageConfig?.components?.length || 0 }}</span>
      </div>
      <div class="status-right">
        <span>画布尺寸: {{ canvasSize.width }} × {{ canvasSize.height }}</span>
      </div>
    </div>
  </div>
</template>

<script setup>
import { computed, ref, onMounted, onUnmounted, inject } from 'vue'
import ComponentRenderer from './ComponentRenderer.vue'

// Props
const props = defineProps({
  pageConfig: {
    type: Object,
    default: null
  },
  dragState: {
    type: Object,
    required: true
  }
})

// Emits
const emit = defineEmits([
  'component-select',
  'component-update',
  'component-delete',
  'drop'
])

// 注入的依赖
const designerStore = inject('designerStore')
const selectedComponent = inject('selectedComponent')
const dragDropManager = inject('dragDropManager')

// 响应式状态
const canvasContainer = ref(null)
const zoomLevel = ref(1)
const zoomMode = ref('fit')
const showGrid = ref(true)
const canvasSize = ref({ width: 1200, height: 800 })

// 计算属性
const canvasStyle = computed(() => ({
  transform: `scale(${zoomLevel.value})`,
  transformOrigin: 'top left',
  width: `${canvasSize.value.width}px`,
  height: `${canvasSize.value.height}px`
}))

const dropHighlightStyle = computed(() => {
  if (!dragState.value.dropTarget) return {}
  
  // 这里可以根据拖拽目标的位置计算高亮区域
  return {
    position: 'absolute',
    top: '0px',
    left: '0px',
    width: '100%',
    height: '100%',
    pointerEvents: 'none'
  }
})

// 方法
const setZoomMode = (mode) => {
  zoomMode.value = mode
  
  if (mode === 'fit') {
    fitToCanvas()
  } else if (mode === '100') {
    zoomLevel.value = 1
  }
}

const zoomIn = () => {
  zoomLevel.value = Math.min(zoomLevel.value * 1.2, 3)
  zoomMode.value = 'custom'
}

const zoomOut = () => {
  zoomLevel.value = Math.max(zoomLevel.value / 1.2, 0.1)
  zoomMode.value = 'custom'
}

const fitToCanvas = () => {
  if (!canvasContainer.value) return
  
  const container = canvasContainer.value
  const containerRect = container.getBoundingClientRect()
  
  const scaleX = containerRect.width / canvasSize.value.width
  const scaleY = containerRect.height / canvasSize.value.height
  const scale = Math.min(scaleX, scaleY, 1) // 不超过100%
  
  zoomLevel.value = scale
}

const resetCanvas = () => {
  zoomLevel.value = 1
  zoomMode.value = '100'
}

const toggleGrid = () => {
  showGrid.value = !showGrid.value
}

const handleDrop = (event) => {
  event.preventDefault()
  
  try {
    const data = JSON.parse(event.dataTransfer.getData('application/json'))
    const rect = canvasContainer.value.getBoundingClientRect()
    
    const position = {
      x: (event.clientX - rect.left) / zoomLevel.value,
      y: (event.clientY - rect.top) / zoomLevel.value
    }
    
    emit('drop', {
      component: data.widget || data.component,
      position,
      targetComponent: dragDropManager.dropTarget.value,
      type: data.type
    })
  } catch (error) {
    console.error('拖拽数据解析失败:', error)
  }
}

const handleDragOver = (event) => {
  dragDropManager.handleDragOver(event)
}

const handleDragLeave = (event) => {
  // 处理拖拽离开逻辑
}

const handleCanvasClick = (event) => {
  // 点击画布空白区域，取消选中
  if (event.target === canvasContainer.value || event.target.classList.contains('canvas-content')) {
    selectedComponent.value = null
    emit('component-select', null)
  }
}

const handleComponentClick = (component, event) => {
  event.stopPropagation()
  emit('component-select', component)
}

const handleComponentDoubleClick = (component, event) => {
  event.stopPropagation()
  // 可以在这里实现编辑模式
}

const handleComponentUpdate = (componentId, updates) => {
  emit('component-update', componentId, updates)
}

const handleComponentDelete = (componentId) => {
  emit('component-delete', componentId)
}

const handleComponentDragStart = (component, event) => {
  // 处理组件拖拽开始
  if (dragDropManager.isDragging.value) return
  
  dragDropManager.startDrag(component, 'move', 'canvas', event)
}

const isComponentSelected = (component) => {
  return selectedComponent.value?.id === component.id
}

// 生命周期
onMounted(() => {
  fitToCanvas()
  
  // 监听窗口大小变化
  window.addEventListener('resize', fitToCanvas)
})

onUnmounted(() => {
  window.removeEventListener('resize', fitToCanvas)
})
</script>

<style scoped>
.design-canvas {
  flex: 1;
  display: flex;
  flex-direction: column;
  background: #f5f5f5;
  overflow: hidden;
}

.canvas-toolbar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 8px 16px;
  background: white;
  border-bottom: 1px solid #e4e7ed;
  gap: 16px;
}

.toolbar-left,
.toolbar-right {
  display: flex;
  align-items: center;
  gap: 8px;
}

.zoom-level {
  font-size: 12px;
  color: #606266;
  margin-left: 8px;
}

.canvas-container {
  flex: 1;
  position: relative;
  overflow: auto;
  background: #fafafa;
  display: flex;
  align-items: center;
  justify-content: center;
}

.canvas-container.show-grid {
  background-image: 
    linear-gradient(rgba(0, 0, 0, 0.1) 1px, transparent 1px),
    linear-gradient(90deg, rgba(0, 0, 0, 0.1) 1px, transparent 1px);
  background-size: 20px 20px;
}

.canvas-content {
  position: relative;
  background: white;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
  border-radius: 8px;
  overflow: hidden;
  padding-top: 16px; /* 减少顶部内边距，因为标签现在在边框上 */
}

.empty-canvas {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
  min-height: 400px;
}

.empty-tip {
  text-align: center;
  color: #909399;
}

.empty-tip i {
  font-size: 48px;
  margin-bottom: 16px;
  display: block;
  opacity: 0.5;
}

.empty-tip h3 {
  margin: 0 0 8px 0;
  font-size: 18px;
  font-weight: 500;
  color: #606266;
}

.empty-tip p {
  margin: 0;
  font-size: 14px;
  color: #909399;
}

.drop-highlight {
  position: absolute;
  pointer-events: none;
  z-index: 1000;
}

.highlight-border {
  border: 2px dashed #409eff;
  background-color: rgba(64, 158, 255, 0.05);
  width: 100%;
  height: 100%;
  border-radius: 4px;
}

.canvas-statusbar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 8px 16px;
  background: white;
  border-top: 1px solid #e4e7ed;
  font-size: 12px;
  color: #909399;
}

.status-left,
.status-right {
  display: flex;
  gap: 16px;
}

/* 滚动条样式 */
.canvas-container::-webkit-scrollbar {
  width: 8px;
  height: 8px;
}

.canvas-container::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 4px;
}

.canvas-container::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 4px;
}

.canvas-container::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}

/* 响应式设计 - 保持水平布局 */
@media (max-width: 1200px) {
  .canvas-toolbar {
    flex-direction: row; /* 保持水平布局 */
    align-items: center; /* 保持居中对齐 */
    gap: 16px; /* 保持原有间距 */
  }
  
  .toolbar-left,
  .toolbar-right {
    justify-content: flex-start; /* 保持左对齐 */
  }
}
</style>
